<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量执行详情"
    width="80%"
    :close-on-click-modal="false"
  >
    <div v-if="batch" class="batch-detail">
      <!-- 批量执行基本信息 -->
      <el-card class="info-card">
        <template #header>
          <div class="card-header">
            <span>执行信息</span>
            <el-tag :type="getStatusType(batch.status)">
              {{ getStatusText(batch.status) }}
            </el-tag>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>执行名称：</label>
              <span>{{ batch.name }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>创建人：</label>
              <span>{{ batch.creator_name }}</span>
            </div>
          </el-col>
        </el-row>
        
        <div class="info-item">
          <label>执行描述：</label>
          <p class="description">{{ batch.description || '无描述' }}</p>
        </div>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>开始时间：</label>
              <span>{{ formatTime(batch.start_time) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>结束时间：</label>
              <span>{{ formatTime(batch.end_time) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>执行时长：</label>
              <span>{{ formatDuration(batch.duration) }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ batch.total_scripts || 0 }}</div>
              <div class="stat-label">总脚本数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ batch.completed_scripts || 0 }}</div>
              <div class="stat-label">已完成</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number success">{{ batch.success_scripts || 0 }}</div>
              <div class="stat-label">成功数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number danger">{{ batch.failed_scripts || 0 }}</div>
              <div class="stat-label">失败数</div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 执行进度 -->
      <el-card class="progress-card">
        <template #header>
          <span>执行进度</span>
        </template>
        
        <div class="progress-info">
          <div class="progress-text">
            {{ getProgressText() }}
          </div>
          <el-progress
            :percentage="getProgressPercentage()"
            :status="getProgressStatus()"
            :stroke-width="20"
          />
        </div>
      </el-card>

      <!-- 脚本执行结果 -->
      <el-card class="executions-card">
        <template #header>
          <span>脚本执行结果</span>
        </template>
        
        <el-table
          v-loading="executionsLoading"
          :data="executionDetails"
          border
          style="width: 100%"
        >
          <el-table-column prop="script_name" label="脚本名称" width="200" />
          <el-table-column prop="execution_name" label="执行名称" width="200" />
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="total_count" label="总任务" width="80" />
          <el-table-column prop="success_count" label="成功" width="80" />
          <el-table-column prop="failed_count" label="失败" width="80" />
          
          <el-table-column prop="duration" label="耗时" width="100">
            <template #default="{ row }">
              {{ formatDuration(row.duration) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="start_time" label="开始时间" width="150">
            <template #default="{ row }">
              {{ formatTime(row.start_time) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="viewExecutionDetail(row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button v-if="batch.status === 'running'" type="warning" @click="stopBatch">
          <el-icon><VideoPause /></el-icon>
          停止执行
        </el-button>
        <el-button type="primary" @click="downloadReport">
          <el-icon><Download /></el-icon>
          下载报告
        </el-button>
      </div>
    </template>

    <!-- 执行详情对话框 -->
    <ExecutionDetailDialog
      v-model:visible="executionDetailVisible"
      :execution="currentExecution"
    />
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoPause, Download } from '@element-plus/icons-vue'
import { getUiAutomationBatchExecution } from '../../api/uiAutomation'
import ExecutionDetailDialog from './ExecutionDetailDialog.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  batch: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible'])

// 响应式数据
const executionsLoading = ref(false)
const executionDetails = ref([])
const executionDetailVisible = ref(false)
const currentExecution = ref(null)

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听器
watch(() => props.visible, (visible) => {
  if (visible && props.batch) {
    loadBatchDetail()
  }
})

// 方法
const loadBatchDetail = async () => {
  executionsLoading.value = true
  try {
    const response = await getUiAutomationBatchExecution(props.batch.id)
    if (response.success && response.data.execution_details) {
      executionDetails.value = response.data.execution_details
    }
  } catch (error) {
    console.error('加载批量执行详情失败:', error)
    ElMessage.error('加载批量执行详情失败')
  } finally {
    executionsLoading.value = false
  }
}

const handleClose = () => {
  dialogVisible.value = false
  executionDetails.value = []
}

const stopBatch = () => {
  // TODO: 实现停止批量执行功能
  ElMessage.info('停止批量执行功能开发中')
}

const downloadReport = () => {
  // TODO: 实现报告下载功能
  ElMessage.info('报告下载功能开发中')
}

const viewExecutionDetail = (execution) => {
  currentExecution.value = execution
  executionDetailVisible.value = true
}

const getProgressText = () => {
  if (!props.batch) return ''
  
  const { completed_scripts, total_scripts } = props.batch
  return `已完成 ${completed_scripts || 0} / ${total_scripts || 0} 个脚本`
}

const getProgressPercentage = () => {
  if (!props.batch || !props.batch.total_scripts) return 0
  
  const { completed_scripts, total_scripts } = props.batch
  return Math.round(((completed_scripts || 0) / total_scripts) * 100)
}

const getProgressStatus = () => {
  if (!props.batch) return ''
  
  const { status, failed_scripts } = props.batch
  if (status === 'failed' || (failed_scripts && failed_scripts > 0)) {
    return 'exception'
  }
  if (status === 'success') {
    return 'success'
  }
  return ''
}

const getStatusType = (status) => {
  const statusMap = {
    'pending': 'info',
    'running': 'warning',
    'success': 'success',
    'failed': 'danger',
    'cancelled': ''
  }
  return statusMap[status] || ''
}

const getStatusText = (status) => {
  const statusMap = {
    'pending': '待执行',
    'running': '执行中',
    'success': '成功',
    'failed': '失败',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString()
}

const formatDuration = (duration) => {
  if (!duration) return '-'
  if (duration < 60) return `${duration}秒`
  const minutes = Math.floor(duration / 60)
  const seconds = duration % 60
  return `${minutes}分${seconds}秒`
}
</script>

<style lang="scss" scoped>
.batch-detail {
  .info-card,
  .progress-card,
  .executions-card {
    margin-bottom: 20px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
  }
  
  .info-item {
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    label {
      font-weight: 600;
      color: #303133;
      margin-right: 8px;
    }
    
    span {
      color: #606266;
    }
    
    .description {
      margin: 8px 0 0 0;
      color: #606266;
      line-height: 1.6;
    }
  }
  
  .stat-item {
    text-align: center;
    
    .stat-number {
      font-size: 20px;
      font-weight: 600;
      color: #303133;
      line-height: 1;
      margin-bottom: 4px;
      
      &.success {
        color: #67c23a;
      }
      
      &.danger {
        color: #f56c6c;
      }
    }
    
    .stat-label {
      font-size: 12px;
      color: #666;
    }
  }
  
  .progress-info {
    .progress-text {
      margin-bottom: 12px;
      font-weight: 600;
      color: #303133;
      text-align: center;
    }
  }
}

.dialog-footer {
  text-align: right;
  
  .el-button {
    margin-left: 8px;
  }
}

:deep(.el-dialog) {
  .el-dialog__body {
    padding: 20px;
    max-height: 80vh;
    overflow-y: auto;
  }
}
</style>
